package com.wxxymakers.grademark.config.realm;

import com.wxxymakers.grademark.model.entity.WxRole;
import com.wxxymakers.grademark.model.entity.WxUser;
import com.wxxymakers.grademark.service.WxUserService;
import com.wxxymakers.grademark.utils.Const;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @AUTHOR soft
 * @DATE 2018/12/21 13:37
 * @DESCRIBE
 */
@Component("realm")
public class WxUserRealm extends AuthorizingRealm {

    private final WxUserService service;

    @Autowired
    public WxUserRealm(WxUserService service) {
        this.service = service;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        WxUser user = service.byUsernameJoin(username);
        WxRole role = user.getRole();
        Set<String> roles = new HashSet<>();
        roles.add("teacher"); // 基本角色 都是老师

        if (role != null) {
            roles.add(role.getSign());
        }
        return new SimpleAuthorizationInfo(roles);
    }

    /**
     * 登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;
        String username = utoken.getUsername();
        WxUser user = service.byUsernameJoin(username);

        if (user == null) {
            throw new UnknownAccountException("用户不存在！请检测您的账号是否错误！");
        }
        if (!user.getPassword().equals(service.toHex(username, String.valueOf(utoken.getPassword())))) {
            throw new UnsupportedTokenException("用户密码错误！");
        }

        // 登录成功 将当前登录的用户信息放入session
        SecurityUtils.getSubject().getSession().setAttribute(Const.CURRENT_USER, user);

        ByteSource byteSource = ByteSource.Util.bytes(username.getBytes());
        return new SimpleAuthenticationInfo(username, user.getPassword(), byteSource, getName());
    }
}
